import 'dart:math';
import 'dart:typed_data';
import 'dart:ui';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:baoan/api.dart';
import 'package:baoan/global.dart';
import 'package:flutter/material.dart';
import 'package:baoan/toast.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: '抑云热评墙',
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key}) : super(key: key);

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  GlobalKey globalKey = GlobalKey();
  var _data;
  var _showBtn = true;
  int _num = 0;

  Future<Uint8List> _capturePng() async {
    setState(() {
      _showBtn = false;
    });

    try {
      Future.delayed(Duration(milliseconds: 100), () async {
        RenderRepaintBoundary boundary =
            globalKey.currentContext.findRenderObject();
        var image = await boundary.toImage(pixelRatio: 3.0);
        ByteData byteData = await image.toByteData(format: ImageByteFormat.png);
        Uint8List pngBytes = byteData.buffer.asUint8List();
        final result = await ImageGallerySaver.saveImage(pngBytes,
            quality: 100, name: "保安日记");
        Toast.show(context,
            msg: '日记保存${result['isSuccess'] ? "成功" : "失败"}', duration: 1);
        setState(() {
          _showBtn = true;
        });
      });
    } catch (e) {
      print(e);
      setState(() {
        _showBtn = true;
      });
    }
    return null;
  }

  @override
  void initState() {
    getData();
    super.initState();
  }

  getData() async {
    setState(() => {_data = null});
    var res = await note(_num++);
    setState(() => {_data = res});
  }

  getFontSize(width, comment) {
    return width / (comment.split('').toList().length / 4);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: _data == null
          ? Container(
              width: MediaQuery.of(context).size.width,
              height: MediaQuery.of(context).size.width * 1.7,
              margin: EdgeInsets.only(top: Global.paddingTop),
              decoration: BoxDecoration(
                color: Global.backgroundColor,
                image: DecorationImage(
                  image: AssetImage("assets/images/bg.png"),
                  repeat: ImageRepeat.noRepeat,
                  fit: BoxFit.fitWidth,
                  alignment: Alignment.topCenter,
                ),
              ),
              child: Center(
                child: CircularProgressIndicator(
                  backgroundColor: Global.backgroundColor,
                  valueColor: AlwaysStoppedAnimation<Color>(Global.fontColor),
                ),
              ),
            )
          : Container(
              width: MediaQuery.of(context).size.width,
              height: MediaQuery.of(context).size.height,
              child: SingleChildScrollView(
                child: Column(
                  children: [
                    RepaintBoundary(
                      key: globalKey,
                      child: Container(
                        width: MediaQuery.of(context).size.width,
                        height: MediaQuery.of(context).size.width * 1.7,
                        margin: EdgeInsets.only(top: Global.paddingTop),
                        decoration: BoxDecoration(
                          image: DecorationImage(
                            image: AssetImage("assets/images/bg.png"),
                            repeat: ImageRepeat.noRepeat,
                            fit: BoxFit.fitWidth,
                            alignment: Alignment.topCenter,
                          ),
                        ),
                        child: Transform.rotate(
                          angle: pi * -0.027,
                          child: Container(
                            decoration: BoxDecoration(),
                            padding: EdgeInsets.fromLTRB(
                                76,
                                MediaQuery.of(context).size.width / 3.65,
                                41,
                                0),
                            child: Column(
                              mainAxisAlignment: MainAxisAlignment.start,
                              crossAxisAlignment: CrossAxisAlignment.center,
                              children: [
                                Row(
                                  mainAxisAlignment:
                                      MainAxisAlignment.spaceAround,
                                  crossAxisAlignment: CrossAxisAlignment.center,
                                  children: [
                                    Text(
                                      _data['date'],
                                      style: TextStyle(
                                        color: Global.fontColor,
                                        fontSize: 20,
                                        fontWeight: FontWeight.w500,
                                        fontFamily: 'MuYao',
                                        height: 1.5,
                                      ),
                                    ),
                                    Text(
                                      '星期' + _data['week'],
                                      style: TextStyle(
                                        color: Global.fontColor,
                                        fontSize:
                                            MediaQuery.of(context).size.width /
                                                17,
                                        fontWeight: FontWeight.w500,
                                        fontFamily: 'MuYao',
                                        height: 1.5,
                                      ),
                                    ),
                                    Text(
                                      _data['weather'],
                                      style: TextStyle(
                                        color: Global.fontColor,
                                        fontSize: 20,
                                        fontWeight: FontWeight.w500,
                                        fontFamily: 'MuYao',
                                        height: 1.5,
                                      ),
                                    ),
                                  ],
                                ),
                                Text(
                                  _data['title'],
                                  style: TextStyle(
                                    color: Global.fontColor,
                                    fontSize:
                                        MediaQuery.of(context).size.width / 17,
                                    fontWeight: FontWeight.w500,
                                    fontFamily: 'MuYao',
                                    height: 1.5,
                                  ),
                                ),
                                Text(
                                  _data['note'],
                                  style: TextStyle(
                                    color: Global.fontColor,
                                    fontSize:
                                        MediaQuery.of(context).size.width / 17,
                                    fontWeight: FontWeight.w500,
                                    height: 1.55,
                                    fontFamily: 'MuYao',
                                  ),
                                ),
                              ],
                            ),
                          ),
                        ),
                      ),
                    ),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceAround,
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        InkWell(
                          onTap: () {
                            getData();
                          },
                          child: Container(
                            width: 150,
                            height: 60,
                            decoration: BoxDecoration(
                              image: DecorationImage(
                                image: AssetImage("assets/images/btn.png"),
                                repeat: ImageRepeat.noRepeat,
                                fit: BoxFit.fill,
                                alignment: Alignment.topCenter,
                              ),
                            ),
                            child: Center(
                              child: Text(
                                '翻页',
                                style: TextStyle(
                                  color: Global.backgroundColor,
                                  fontSize: 30,
                                  fontWeight: FontWeight.w500,
                                  fontFamily: 'MuYao',
                                ),
                              ),
                            ),
                          ),
                        ),
                        InkWell(
                          onTap: () {
                            _capturePng();
                          },
                          child: Container(
                            width: 150,
                            height: 60,
                            decoration: BoxDecoration(
                              image: DecorationImage(
                                image: AssetImage("assets/images/btn.png"),
                                repeat: ImageRepeat.noRepeat,
                                fit: BoxFit.fill,
                                alignment: Alignment.topCenter,
                              ),
                            ),
                            child: Center(
                              child: Text(
                                '保存日记',
                                style: TextStyle(
                                  color: Global.backgroundColor,
                                  fontSize: 27,
                                  fontWeight: FontWeight.w500,
                                  fontFamily: 'MuYao',
                                ),
                              ),
                            ),
                          ),
                        )
                      ],
                    )
                  ],
                ),
              ),
            ),
    );
  }
}
